// components/actionSheet/actionSheet.js
const app = getApp()
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    actionSheetData: Object,
    isLike: true,
    showGoodsAction: Boolean,
    index: Number,
    isBuy: Boolean
  },

  /**
   * 组件的初始数据
   */
  data: {
    actionAct: 0, // 商品分类选择
  },

  /**
   * 组件的方法列表
   */
  methods: {
    preventTouchMove(e){
      e.preventDefault(); // 阻止默认的触摸移动行为
    },
    onClose(){
      this.setData({ showGoodsAction: false })
    },
    // 切换商品选中
    switchGoods(e){
      const idx = e.currentTarget.dataset.idx
      this.setData({ 
        actionAct: idx,
        'actionSheetData.actIdx': idx
       })
    },
    isExist(){
      let { actionSheetData, actionAct } = this.data;
      // 先从本地存储读取 goodsList，如果没有则创建一个空数组
      let currentGoodsList = wx.getStorageSync('goodsList') || []
      let isIdExists = currentGoodsList.some(item => item._id === actionSheetData._id && item.actIdx === actionAct)

      if(isIdExists){
        wx.showToast({
          title: '购物车已经有啦',
          icon: 'none',
          duration: 1000
        })
        return true
      }
    },
    // 购物车页更换产品
    newGoods(){
      let obj = wx.getStorageSync('goodsList')
      obj.splice(this.data.index,1,this.data.actionSheetData)
      wx.setStorageSync('goodsList', obj)

      this.triggerEvent('updateGoods')
      this.setData({
        showGoodsAction: false
      })

    },
    // 产品加入购物车
    addCart(){
      if(this.isExist()) return
      if(this.data.isLike){
        this.newGoods()
        return
      }
      
      let currentGoodsList = wx.getStorageSync('goodsList') || []
      let { actionSheetData, actionAct } = this.data;
      let actData = actionSheetData
      actData.actIdx = actionAct
      actData.isSelected = false

      currentGoodsList.unshift(actData)
      wx.setStorageSync('goodsList', currentGoodsList)

      this.triggerEvent('setGoodsNum')

      this.setData({
        showGoodsAction: false
      })
    },
    // 立即购买
    onBuy(){
      app.globalData.settleGoods = [] // 先把购买的商品清空
      this.onClose()

      let buyData = this.data.actionSheetData
      buyData.actIdx = this.data.actionAct

      app.globalData.settleGoods.push(buyData)

      wx.navigateTo({
        url: '../../subpkg_settle/pages/settle'
      })
      
    }
  }
})